<template>
  <div class="container">
    <div v-loading="loading" element-loading-text="加载中..." class="app-container">
      <el-button class="btn-add" size="mini" type="primary" @click="addPermission(0,1)">添加权限</el-button>
      <el-table :data="treeList" default-expand-all row-key="id">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button v-if="row.type === 1" size="mini" type="text" @click="addPermission(row.id,2)">添加</el-button>
            <el-button size="mini" type="text" @click="Edit(row.id)">编辑</el-button>
            <el-popconfirm title="确定删除这项数据吗？" @onConfirm="Del(row.id)">
              <el-button slot="reference" style="margin-left: 10px;" size="mini" type="text">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" style="height:40px" align="middle" justify="end">
        <el-pagination :total="total" layout="total" style="margin-right: 20px;" />
      </el-row>
    </div>
    <Dialog ref="permissionDialog" @success="success" />
  </div>
</template>

<script>
import Dialog from './components/Dialog.vue'
import { getPermissionList, delPermission } from '@/api/permission.js'
import { transListToTreeData } from '@/utils/index.js'
import { mapActions } from 'vuex'
export default {
  name: 'Permission',
  components: {
    Dialog
  },
  data() {
    return {
      treeList: [],
      total: null, // 总条数
      loading: false
    }
  },
  created() {
    this.GetPermissionList()
  },
  methods: {
    ...mapActions('user', ['getUserInfo']),
    // 获取权限列表
    async GetPermissionList() {
      this.loading = true
      const res = await getPermissionList()
      console.log(res)
      this.total = res.length
      this.treeList = transListToTreeData(res, 0)
      this.loading = false
    },
    // 添加权限
    addPermission(pid, type) {
      this.$refs.permissionDialog.showDialog = true
      this.$refs.permissionDialog.formData.pid = pid // 需要知道添加到哪个节点下了 0代表根节点
      this.$refs.permissionDialog.formData.type = type // 一级添加的type为1 二级type为2
    },
    // 编辑权限
    Edit(id) {
      this.$refs.permissionDialog.showDialog = true
      this.$refs.permissionDialog.GetPermissionDetail(id)
    },
    // 删除权限
    async Del(id) {
      const res = await delPermission(id)
      console.log(res)
      this.GetPermissionList()
      this.$message.success('删除权限成功')
    },
    // 接收更新
    success() {
      this.GetPermissionList()
      this.getUserInfo() // 重新获取用户基本信息
    }
  }
}
</script>

<style lang="scss" scoped>
.btn-add {
  margin: 10px;
}
</style>
